package org.example.mallsystem1104.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.mallsystem1104.common.Result;
import org.example.mallsystem1104.constants.Constants;
import org.example.mallsystem1104.entity.Good;
import org.example.mallsystem1104.entity.GoodStandard;
import org.example.mallsystem1104.exception.ServiceException;
import org.example.mallsystem1104.mapper.GoodMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static org.example.mallsystem1104.constants.RedisConstants.GOOD_TOKEN_KEY;
import static org.example.mallsystem1104.constants.RedisConstants.GOOD_TOKEN_TTL;

@Service
public class GoodService extends ServiceImpl<GoodMapper, Good> {

    @Resource
    private GoodMapper goodMapper;
    @Resource
    private RedisTemplate<String, Good> redisTemplate;

    public Object findAll() {
        return goodMapper.findAllGoods();
    }

    public Object getGoodById(Long id) {
        //rediskey=good:id:3
        String rediskey=GOOD_TOKEN_KEY+id;
        //先从redis里查，如果有商品信息则返回前端
        ValueOperations<String, Good> valueOperations = redisTemplate.opsForValue();
        Good redisGood= valueOperations.get(rediskey);
        if (redisGood!=null){
            //更新redis过期时间
            redisTemplate.expire(rediskey,GOOD_TOKEN_TTL, TimeUnit.MINUTES);
            return redisGood;
        }
        //如果redis里没有商品信息，则从数据库里查
        LambdaQueryWrapper<Good> query=new LambdaQueryWrapper<Good>();
        //Good里面是否有isdelete值等于false并且id=传进来的id的商品
        query.eq(Good::getIsDelete,false);
        query.eq(Good::getId,id);
        //有的话则用Good接收返回
        Good dbGood=getOne(query);
        //判断good是否为空，若不为空则把商品信息传回redis
        if (dbGood!=null){
            //将商品信息存入redis
            valueOperations.set(rediskey,dbGood);
            redisTemplate.expire(rediskey,GOOD_TOKEN_TTL, TimeUnit.MINUTES);
            return dbGood;
        }
        throw new ServiceException(Constants.NO_RESULT,"无结果");

    }

    public Object getStandardById(Long id) {
//        LambdaQueryWrapper<GoodStandard> queryWrapper1=new LambdaQueryWrapper<>();
//        queryWrapper1.eq(GoodStandard::getGoodId,id);
//        List<GoodStandard> standards=getOne(queryWrapper1)；
        List<GoodStandard> standards=goodMapper.getStandardById(id);
        if (standards.size()==0){
            return Result.error(Constants.NO_RESULT,"无结果");
        }
        return JSON.toJSONString(standards);

    }
}
